import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/bill_provider.dart';
import '../../models/bill.dart';
import '../../models/bill_item.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart';

class BillDetailScreen extends StatefulWidget {
  final int billId;

  const BillDetailScreen({super.key, required this.billId});

  @override
  State<BillDetailScreen> createState() => _BillDetailScreenState();
}

class _BillDetailScreenState extends State<BillDetailScreen> {
  Bill? _bill;
  List<BillItem> _billItems = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadBillData();
  }

  Future<void> _loadBillData() async {
    try {
      final billProvider = Provider.of<BillProvider>(context, listen: false);
      final bill = await billProvider.getBillById(widget.billId);
      final billItems = await billProvider.getBillItems(widget.billId);
      
      setState(() {
        _bill = bill;
        _billItems = billItems;
        _isLoading = false;
      });
    } catch (e) {
      SnackbarHelper.showError(context, '加载账单详情失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _updateBillStatus(String status) async {
    try {
      final billProvider = Provider.of<BillProvider>(context, listen: false);
      await billProvider.updateBillStatus(widget.billId, status);
      SnackbarHelper.showSuccess(context, '账单状态更新成功');
      _loadBillData(); // 重新加载数据
    } catch (e) {
      SnackbarHelper.showError(context, '更新状态失败: $e');
    }
  }

  // 修改状态更新对话框
  void _showStatusUpdateDialog() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('更新账单状态'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('请选择新的状态：'),
            SizedBox(height: 16),
            Text('• 未完成：账单还在进行中，可编辑'),
            Text('• 已完成：账单已结清，不可编辑'),
            Text('• 已取消：账单作废，不可编辑'),
          ],
        ),
        actions: [
          SizedBox(
            width: double.infinity,
            child: TextButton(
              onPressed: () => Navigator.of(ctx).pop(),
              child: const Text('关闭'),
            ),
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: () {
                    Navigator.of(ctx).pop();
                    _verifyPasswordAndUpdateStatus('completed');
                  },
                  style: OutlinedButton.styleFrom(
                    foregroundColor: Colors.green,
                    side: const BorderSide(color: Colors.green),
                  ),
                  child: const Text('标记为已完成'),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: OutlinedButton(
                  onPressed: () {
                    Navigator.of(ctx).pop();
                    _updateBillStatus('cancelled');
                  },
                  style: OutlinedButton.styleFrom(
                    foregroundColor: Colors.red,
                    side: const BorderSide(color: Colors.red),
                  ),
                  child: const Text('标记为已取消'),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _verifyPasswordAndUpdateStatus(String status) {
    final TextEditingController passwordController = TextEditingController();
    final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
    
    // 预设密码，实际应用中应该从配置或用户设置中读取
    const correctPassword = "123456";
    
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('身份验证'),
        content: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('为了确保操作安全，请输入管理员密码'),
              const SizedBox(height: 16),
              TextFormField(
                controller: passwordController,
                obscureText: true,
                decoration: const InputDecoration(
                  labelText: '密码',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入密码';
                  }
                  return null;
                },
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                if (passwordController.text == correctPassword) {
                  Navigator.of(ctx).pop();
                  _updateBillStatus(status);
                } else {
                  SnackbarHelper.showError(context, '密码错误，请重试');
                }
              }
            },
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('账单详情', style: AppTheme.titleLarge),
        actions: [
          if (_bill != null && _bill!.status == 'pending')
            IconButton(
              icon: const Icon(Icons.edit),
              onPressed: _showStatusUpdateDialog,
              tooltip: '更新状态',
            ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _bill == null
              ? const Center(child: Text('账单不存在'))
              : _buildBillDetail(),
    );
  }

  Widget _buildBillDetail() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 账单基本信息卡片
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        _bill!.restaurantName,
                        style: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: _getStatusColor(_bill!.status).withOpacity(0.1),
                          borderRadius: BorderRadius.circular(4),
                          border: Border.all(color: _getStatusColor(_bill!.status)),
                        ),
                        child: Text(
                          _getStatusText(_bill!.status),
                          style: TextStyle(
                            color: _getStatusColor(_bill!.status),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  // 突出显示账单时间
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    decoration: BoxDecoration(
                      color: Colors.blue.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.blue),
                    ),
                    child: Row(
                      children: [
                        const Icon(Icons.calendar_today, color: Colors.blue, size: 18),
                        const SizedBox(width: 8),
                        Text(
                          '账单时间: ${_formatDate(_bill!.customDate ?? _bill!.billDate)}',  // 使用 customDate
                          style: const TextStyle(
                            fontSize: 16,
                            color: Colors.blue,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 12),
                  Text('创建时间: ${_formatDate(_bill!.createdAt)}'),
                  const SizedBox(height: 6),
                  Text('总金额: ¥${_bill!.totalAmount.toStringAsFixed(2)}'),
                  if (_bill!.notes != null && _bill!.notes!.isNotEmpty) ...[
                    const SizedBox(height: 6),
                    Text('备注: ${_bill!.notes}'),
                  ],
                ],
              ),
            ),
          ),
          
          const SizedBox(height: 16),
          
          // 账单项目卡片（保持不变）
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '账单项目',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 12),
                  if (_billItems.isEmpty)
                    const Padding(
                      padding: EdgeInsets.all(16.0),
                      child: Text(
                        '暂无商品项目',
                        style: TextStyle(color: Colors.grey),
                        textAlign: TextAlign.center,
                      ),
                    )
                  else
                    ..._billItems.map((item) => _buildBillItem(item)).toList(),
                  
                  const SizedBox(height: 8),
                  const Divider(),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        '总计:',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                      Text(
                        '¥${_bill!.totalAmount.toStringAsFixed(2)}',
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Colors.green,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  
  Widget _buildBillItem(BillItem item) {
    final isReturnItem = item.quantity < 0;
    
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        contentPadding: EdgeInsets.zero,
        leading: CircleAvatar(
          backgroundColor: isReturnItem ? Colors.orange : Colors.blue,
          child: Text(
            item.quantity.abs().toString(),
            style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
        title: Row(
          children: [
            Text(
              item.productName,
              style: const TextStyle(fontWeight: FontWeight.w500),
            ),
            if (isReturnItem) ...[
              const SizedBox(width: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: Colors.orange,
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Text(
                  '退货',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 10,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ],
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 4),
            Text('${item.productSpec} × ¥${item.unitPrice.toStringAsFixed(2)}'),
          ],
        ),
        trailing: Text(
          '¥${item.subtotal.toStringAsFixed(2)}',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: isReturnItem ? Colors.orange : Colors.green,
          ),
        ),
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'pending':
        return Colors.orange;
      case 'completed':
        return Colors.green;
      case 'cancelled':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(String status) {
    switch (status) {
      case 'pending':
        return '未完成';
      case 'completed':
        return '已完成';
      case 'cancelled':
        return '已取消';
      default:
        return '未知';
    }
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
  }
}